package com.yt.lxh.activity.service.impl;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.yt.lxh.activity.service.CouponInfoService;
import com.yt.lxh.constant.MQConst;
import com.yt.lxh.enums.CouponStatus;
import com.yt.lxh.message.PublishOrExpireCouponMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@Service
public class listenCouponNotify {

    @Autowired
    private CouponInfoService couponInfoService;

    // 监听 优惠券发布 / 过期
    @RabbitListener(queues = MQConst.COUPON_PUBLISH_DELAYED_QUEUE)
    public void receiveCouponPublish(Message message, Channel channel) throws IOException {
        // 解析消息
        String s = new String(message.getBody());
        PublishOrExpireCouponMessage m = JSON.parseObject(s, PublishOrExpireCouponMessage.class);
        // 根据 是发布还是过期 执行不同的逻辑
        CouponStatus couponStatus = m.isStatus() ? CouponStatus.RUNNING : CouponStatus.ENDED;
        couponInfoService.updateCouponStatusById(m.getCouponId(), couponStatus);
        // 手动确认收到消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}
